package net.xju3_4.dao;

import net.xju3_4.common.utils.JdbcUtilsV1;
import net.xju3_4.entity.UserEntity;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 用户资料数据访问层
 * 独立的用户资料管理数据访问层
 */
public class UserProfileDao {
    
    /**
     * 根据用户ID查询用户信息
     */
    public UserEntity selectUserById(String userId) {
        // 使用明确的字段列表和别名映射，确保正确映射到实体类属性
        String sql = "SELECT " +
                "id, " +
                "username, " +
                "password, " +
                "phone, " +
                "real_name AS realName, " +  // 映射到实体类 realName
                "id_card_encrypted AS idCardEncrypted, " +  // 映射到实体类 idCardEncrypted
                "driver_license_encrypted AS driverLicenseEncrypted, " +  // 映射到实体类 driverLicenseEncrypted
                "avatar_url AS avatarUrl, " +  // 映射到实体类 avatarUrl
                "status " +
                "FROM user WHERE id = ?";

        try {
            System.out.println("DEBUG: UserProfileDao.selectUserById - userId: " + userId);
            System.out.println("DEBUG: SQL: " + sql);

            Connection conn = JdbcUtilsV1.getConnection();
            UserEntity result = JdbcUtilsV1.executeQueryOne(conn, UserEntity.class, sql, userId);

            if (result != null) {
                System.out.println("DEBUG: 查询成功 - 用户信息: " + result.toString());
            } else {
                System.out.println("DEBUG: 未找到用户ID为 " + userId + " 的用户");
            }

            return result;
        } catch (Exception e) {
            System.out.println("DEBUG: UserProfileDao.selectUserById 异常: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 更新用户资料
     */
    public boolean updateUserProfile(String userId, String realName, String phone, String avatarUrl, String idCard, String driverLicense) {
        StringBuilder sql = new StringBuilder("UPDATE user SET ");
        boolean hasUpdate = false;

        if (realName != null && !realName.trim().isEmpty()) {
            sql.append("real_name = ?, ");
            hasUpdate = true;
        }

        if (phone != null && !phone.trim().isEmpty()) {
            sql.append("phone = ?, ");
            hasUpdate = true;
        }

        if (avatarUrl != null && !avatarUrl.trim().isEmpty()) {
            sql.append("avatar_url = ?, ");
            hasUpdate = true;
        }

        if (idCard != null && !idCard.trim().isEmpty()) {
            sql.append("id_card_encrypted = ?, ");
            hasUpdate = true;
        }

        if (driverLicense != null && !driverLicense.trim().isEmpty()) {
            sql.append("driver_license_encrypted = ?, ");
            hasUpdate = true;
        }

        if (!hasUpdate) {
            System.out.println("DEBUG: 没有需要更新的字段");
            return false;
        }

        // 移除最后的逗号和空格
        sql.setLength(sql.length() - 2);
        sql.append(" WHERE id = ?");

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = JdbcUtilsV1.getConnection();
            pstmt = conn.prepareStatement(sql.toString());

            System.out.println("DEBUG: 执行SQL: " + sql.toString());
            System.out.println("DEBUG: 更新用户ID: " + userId);

            int paramIndex = 1;

            if (realName != null && !realName.trim().isEmpty()) {
                pstmt.setString(paramIndex++, realName);
                System.out.println("DEBUG: 设置realName: " + realName);
            }

            if (phone != null && !phone.trim().isEmpty()) {
                pstmt.setString(paramIndex++, phone);
                System.out.println("DEBUG: 设置phone: " + phone);
            }

            if (avatarUrl != null && !avatarUrl.trim().isEmpty()) {
                pstmt.setString(paramIndex++, avatarUrl);
                System.out.println("DEBUG: 设置avatarUrl: " + avatarUrl);
            }

            if (idCard != null && !idCard.trim().isEmpty()) {
                pstmt.setString(paramIndex++, idCard);
                System.out.println("DEBUG: 设置idCard: " + idCard);
            }

            if (driverLicense != null && !driverLicense.trim().isEmpty()) {
                pstmt.setString(paramIndex++, driverLicense);
                System.out.println("DEBUG: 设置driverLicense: " + driverLicense);
            }

            pstmt.setString(paramIndex, userId);

            int result = pstmt.executeUpdate();
            System.out.println("DEBUG: 更新结果: " + result + " 行受影响");
            return result > 0;

        } catch (SQLException e) {
            System.out.println("DEBUG: 数据库更新失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (pstmt != null) pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JdbcUtilsV1.close();
        }

        return false;
    }
    
    /**
     * 更新密码
     */
    public boolean updatePassword(String userId, String newPassword) {
        String sql = "UPDATE user SET password = ? WHERE id = ?";

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = JdbcUtilsV1.getConnection();
            pstmt = conn.prepareStatement(sql);

            pstmt.setString(1, newPassword);
            pstmt.setString(2, userId);

            return pstmt.executeUpdate() > 0;

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (pstmt != null) pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JdbcUtilsV1.close();
        }

        return false;
    }
    
    /**
     * 更新头像
     */
    public boolean updateAvatar(String userId, String avatarUrl) {
        String sql = "UPDATE user SET avatar_url = ? WHERE id = ?";

        try {
            int result = JdbcUtilsV1.executeUpdate(sql, avatarUrl, userId);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 检查手机号是否已存在
     */
    public boolean checkPhoneExists(String phone, String excludeUserId) {
        String sql = "SELECT COUNT(*) FROM user WHERE phone = ? AND id != ?";

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtilsV1.getConnection();
            pstmt = conn.prepareStatement(sql);

            pstmt.setString(1, phone);
            pstmt.setString(2, excludeUserId);

            rs = pstmt.executeQuery();

            if (rs.next()) {
                return rs.getInt(1) > 0;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JdbcUtilsV1.close();
        }

        return false;
    }
    
    /**
     * 更新身份证信息
     */
    public boolean updateIdCard(String userId, String idCardEncrypted) {
        String sql = "UPDATE user SET id_card_encrypted = ? WHERE id = ?";

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = JdbcUtilsV1.getConnection();
            pstmt = conn.prepareStatement(sql);

            pstmt.setString(1, idCardEncrypted);
            pstmt.setString(2, userId);

            return pstmt.executeUpdate() > 0;

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (pstmt != null) pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JdbcUtilsV1.close();
        }

        return false;
    }

    /**
     * 更新驾驶证信息
     */
    public boolean updateDriverLicense(String userId, String driverLicenseEncrypted) {
        String sql = "UPDATE user SET driver_license_encrypted = ? WHERE id = ?";

        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            conn = JdbcUtilsV1.getConnection();
            pstmt = conn.prepareStatement(sql);

            pstmt.setString(1, driverLicenseEncrypted);
            pstmt.setString(2, userId);

            return pstmt.executeUpdate() > 0;

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (pstmt != null) pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            JdbcUtilsV1.close();
        }

        return false;
    }
    
    /**
     * 更新用户状态
     */
    public boolean updateUserStatus(String userId, Integer status) {
        String sql = "UPDATE user SET status = ? WHERE id = ?";
        
        try (Connection conn = JdbcUtilsV1.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setInt(1, status);
            pstmt.setString(2, userId);
            
            return pstmt.executeUpdate() > 0;
            
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return false;
    }
    
    /**
     * 将ResultSet映射为UserEntity对象
     */
    private UserEntity mapResultSetToUser(ResultSet rs) throws SQLException {
        UserEntity user = new UserEntity();
        
        user.setId(rs.getInt("id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setPhone(rs.getString("phone"));
        user.setRealName(rs.getString("real_name"));
        user.setIdCardEncrypted(rs.getString("id_card_encrypted"));
        user.setDriverLicenseEncrypted(rs.getString("driver_license_encrypted"));
        user.setAvatarUrl(rs.getString("avatar_url"));
        user.setStatus(rs.getInt("status"));
        
        return user;
    }
}
